<template>
	<view class="content pageBg">
		<nav-bar :header="userInfo.avatar" :score="userInfo.score" :usertype="usertype" :level="level" @addScoreClick="addScoreClick"
			@userInfoClick="userInfoClick" @rankClick="rankClick"></nav-bar>
		<view class="suggest" @click="suggestClick">
			<image class="coin" src="../../static/ic_suggest.png" mode="aspectFill"></image>
		</view>
		<view class="main">
			<view class="item" v-for="(item,index)  in dataList" :key="item" @click="itemClick(item,index)">
				<view class="bg">
					<image :src="item.bg" mode="aspectFill"></image>
					<view class="new" v-if="item.isNew">
						<image src="../../static/ic_new.png" mode="aspectFill"></image>
					</view>
				</view>
				<view class="text">
					{{item.name}}
				</view>
				<view class="score" @click="$emit('addScoreClick')" v-if="usertype != 1">
					<image class="coin" src="../../static/shouye/ic_coin.png" mode="aspectFill"></image>
					<view class="money" >
						50
					</view>
				</view>
				
				
			</view>
		</view>
		
	
	</view>

	<view>
		<!-- 提示窗示例 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="base" cancelText="取消" confirmText="观看广告修改一次" title="用户信息每个自然月只可以修改一次"
				@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref
	} from "vue"
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app"
	import {
		getUserOpenId
	} from "../../utils/getOpenId";
	import {
		onShareAppMessage,
		onShareTimeline
	} from "@dcloudio/uni-app";
	import {
		getTotalUserScore,
		getUserScoreFromCloud,
		saveUserTotalScoreToCloud,
		getUserScore,
		addUserScore,
		saveUserAddScoreToLocal,
		SignInGetScore,
		SignInGetScoreLocal,
		saveUserCloudScoreToLocal
	} from '../../store/scoreManager.js'
	import {
		getTodayDateString,
		getTodayMonthString
	} from '../../utils/common.js'
	import {
		md5
	} from 'js-md5';
	const alertDialog = ref(null);
	const score = ref(0);
	const level = ref(1);
	const dataList = ref([])
	let userInfo = ref({})
	const db = uniCloud.database();
	let usertype = 1;
	let isfirst = false;
	// 若在开发者工具中无法预览广告，请切换开发者工具中的基础库版本
	// 在页面中定义激励视频广告
	let videoAd = null
	// 若在开发者工具中无法预览广告，请切换开发者工具中的基础库版本
	// 在页面中定义插屏广告
	let interstitialAd = null
	
	// 判断用户是否是新用户 时间点>3天
	let isNewUser = false
	onLoad((e) => {
		// 在页面onLoad回调事件中创建激励视频广告实例
		if (wx.createRewardedVideoAd) {
			videoAd = wx.createRewardedVideoAd({
				adUnitId: 'adunit-b5c90278c107a744'
			})
			videoAd.onLoad(() => {})
			videoAd.onError((err) => {
				console.error('激励视频光告加载失败', err)
			})
			videoAd.onClose((res) => {
				// 用户点击了【关闭广告】按钮
				if (res && res.isEnded) {
					// 正常播放结束，可以下发游戏奖励
					console.log("观看完毕");
					userInfo.value.score = SignInGetScore()
				} else {
					// 播放中途退出，不下发游戏奖励
					console.log("中途退出");
				}
			})
		}
		usertype = uni.getStorageSync("userType");
		if (!usertype) {
			usertype = 1;
		}
		isfirst = true;
		
		// 在页面onLoad回调事件中创建插屏广告实例
		if (wx.createInterstitialAd) {
		  interstitialAd = wx.createInterstitialAd({
		    adUnitId: 'adunit-1722f7e6276cc54a'
		  })
		  interstitialAd.onLoad(() => {})
		  interstitialAd.onError((err) => {
		    console.error('插屏广告加载失败', err)
		  })
		  interstitialAd.onClose(() => {})
		}
	})
	
	onShow(async () => {
		userInfo.value.score = getUserScore();
		db.collection("guaguale-list-app").where({
			version: 205
		}).orderBy('index asc').get().then(res => {
			if (res.result.data && res.result.data.length > 0) {
				dataList.value = res.result.data;
			}
		}).catch(e=>{
			console.log("guaguale-list-app error:"+ JSON.stringify(e));
		});
	})
	
	function loadHomeAd(){
		const key = "shouyeADCount";
		const count = uni.getStorageSync(key);
		const day = getTodayDateString();
		if(count){
			const c = count.split("--");
			if(c[0] == day){
				if(Number(c[1]) < 3 ){
					loadAD()
					uni.setStorageSync(key,day + "--" + (Number(c[1]) + 1))
				}
			}else{
				loadAD()
				uni.setStorageSync(key,day+"--"+1)
			}
		}else{
			loadAD()
			uni.setStorageSync(key,day+"--"+1)
		}
	}
	
	function loadAD(){
		// 在适合的场景显示插屏广告
		if (interstitialAd) {
		  interstitialAd.show().catch((err) => {
		    console.error('插屏广告显示失败', err)
		  })
		}
	}

	// 用户头像点击
	function userInfoClick() {
		if (usertype === 2) {
			// 每个自然月只能修改一次
			const currentMonth = getTodayMonthString()
			if (userInfo.value.updateuserdate && userInfo.value.updateuserdate == currentMonth) {
				alertDialog.value.open()
			} else {
				uni.navigateTo({
					url: '/pages/register/userinfo'
				})
			}
		}
	}
	
	function suggestClick(e){
		uni.navigateTo({
			url: '/pages/index/suggest?'+ 'usertype=' + usertype
		})
	}
	
	function dialogConfirm(){
		if (videoAd) {
			videoAd.show().catch(() => {
				// 失败重试
				videoAd.load()
					.then(() => videoAd.show())
					.catch(err => {
						console.error('激励视频 广告显示失败', err)
						uni.showToast({
							title: '广告拉取失败，请检查网络状况后重试',
							icon: "none",
							duration: 1500
						})
					})
			})
		}
	}
	
	function dialogClose(){
		alertDialog.value.close()
	}
	
	function rankClick(){
		uni.navigateTo({
			url: '/pages/index/rank?'+ '&usertype=' + usertype
		})
	}

	// 添加积分
	function addScoreClick() {
		// 用户触发广告后，显示激励视频广告
		userInfo.value.score = SignInGetScoreLocal();
		return;
		if (usertype === 2) {
			// userInfo.value.score = SignInGetScore()
			if (videoAd) {
				videoAd.show().catch(() => {
					// 失败重试
					videoAd.load()
						.then(() => videoAd.show())
						.catch(err => {
							console.error('激励视频 广告显示失败', err)
							uni.showToast({
								title: '广告拉取失败，请检查网络状况后重试',
								icon: "none",
								duration: 1500
							})
						})
				})
			}
		} else {
			userInfo.value.score = SignInGetScoreLocal();
		}
	}

	async function itemClick(item, index) {
		if (usertype === 2) {
			if (userInfo.value.score >= 50) {
				userInfo.value.score = saveUserAddScoreToLocal(-50);
				// console.log(item + index);
				const urlStr = '/pages/detail/detail' + (item.type) + '?itemDetail=' + JSON.stringify(item)+
					'&isNewUser=' + isNewUser;
				// const urlStr = '/pages/detail/details'+'?itemDetail=' + JSON.stringify(item);
				// url: `/pages/taskDetails/taskDetails?id=${id}`,
				uni.navigateTo({
					url: urlStr
				})
			} else {
				uni.showToast({
					title: '积分不够了',
					icon: "none",
					duration: 1500
				})
			}
		} else {
			// userInfo.value.score = addUserScore(-50);
			// if (userInfo.value.score >= 0) {
				// const urlStr = '/pages/detail/detail5';
				const urlStr = '/pages/detail/detail' + (item.type) + '?title=' + item.name + '&usertype=' + usertype +
					'&cost=' + item.cost +'&itemDetail=' + JSON.stringify(item);
				uni.navigateTo({
					url: urlStr
				})
			// }
		}
	}

	//分享给好友
	// onShareAppMessage((e) => {
	// 	return {
	// 		title: "喜乐刮刮卡",
	// 		path: "/pages/index/shouye"
	// 	}
	// })

	// //分享朋友圈
	// onShareTimeline(() => {
	// 	return {
	// 		title: "喜乐刮刮卡",
	// 		path: "/pages/index/shouye"
	// 	}
	// })
</script>

<style lang="scss">
	@font-face {
		font-family: NumFont;
		src: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/font/HONORSans-Bold.ttf');
	}
	


	.main {
		position: relative;
		width: 100%;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		row-gap: 50rpx;
		column-gap: 50rpx;
		padding: 50rpx;

		.item {
			width: 300rpx;
			height: 450rpx;
			margin-top: 20rpx;
			position: relative;
			
			
			.bg {

				left: 0rpx;
				top: 0rpx;
				image {
					border-radius: 20rpx;
					width: 100%;
					height: 100%;
				}
				
				.new{
					position: absolute;
					z-index: 100;
					left: 0rpx;
					top: 0rpx;
					border-radius: 10rpx;
					width: 100rpx;
					height: 100rpx;
					image{
						width: 100%;
						height: 100%;
					}
				}
			}

			.text {
				position: absolute;
				text-align: center;
				width: 100%;
				top: 200rpx;
				left: 0;
				color: white;
				font-family: 'NumFont';
				font-size: 60rpx;
				background-color: rgba(0, 0, 0, 0.5);
				font-weight: bold;
			}

			.score {
				position: absolute;
				top: 10rpx;
				right: 10rpx;
				height: 60rpx;
				width: 150rpx;
				align-items: center;
				display: flex;
				flex-direction: row;
				font-size: 20px;
				font-weight: 500;
				margin-left: 30rpx;
				padding: 5rpx 10rpx;
				border-radius: 45rpx;
				background-color: rgba(0, 0, 0, 0.5);
				.coin {
					height: 50rpx;
					width: 50rpx;
				}
				.money {
					color: white;
					margin-left: 20rpx;
					margin-right: 20rpx;
				}
			}
		
		}
	}

	.header {
		position: relative;
		top: 0;
		left: 0;
		width: 100%;
		height: 166rpx;
		background-color: transparent;
		/* background-color: black; */
		display: flex;
		flex-direction: row;
		align-items: bottom;

		.level {
			bottom: 10rpx;
			height: 60rpx;
			color: black;
		}

	}

	.content {
		position: absolute;
		width: 100%;
		height: 100%;

		/* background-image: url("/static/bg.png");
		background-size: cover; */
	}
	
	

	.bg {
		position: absolute;
		width: 100%;
		height: 100%;
	}
	
	.suggest{
		z-index: 1000;
		position: fixed;
		bottom: 100rpx;
		right: 50rpx;
		width: 100rpx;
		height: 100rpx;
		image{
			width: 100%;
			height: 100%;
		}
	}

</style>